<template>
  <div class="music-player">
    🎼
    <el-tooltip :content="isPlaying ? '点击暂停(刷新页面切歌🎶) 当前播放: ' + currentMusic.name : '点击播放音乐'" placement="bottom"
      effect="dark">
      <template #content>
        <div class="music-player-tooltip" v-if="isPlaying">
          <p>点击暂停(刷新页面切歌🎶)</p>
          <p style="color: #4a90e2;">当前播放: {{ currentMusic.name }}</p>
        </div>
        <div class="music-player-tooltip" v-else> 
          点击或按下空格播放音乐 
        </div>
      </template>
      <img :class="['album-cover', { rotating: isPlaying }]" src="@/assets/image/musicPic.png" alt="Album Cover"
        @click="requestAutoplayPermission" />
    </el-tooltip>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElTooltip } from 'element-plus';
import music1 from '@/assets/harvest-symphony.mp3';
import music2 from '@/assets/summer-memories.mp3';
import music3 from '@/assets/Symphony.mp3';
import music4 from '@/assets/What Makes You Beautiful.mp3';
import music5 from '@/assets/为你写诗.mp3';


// 定义多个音频文件路径
const musicFiles = [
  { path: music1, name: 'harvest-symphony(交响乐)' },
  { path: music2, name: 'summer-memories(交响乐)' },
  { path: music3, name: 'Symphony' },
  { path: music4, name: 'What Makes You Beautiful' },
  { path: music5, name: '为你写诗' }
];

// 随机选择一个音频文件
const getRandomMusic = () => {
  const randomIndex = Math.floor(Math.random() * musicFiles.length);
  return musicFiles[randomIndex];
};

const currentMusic = ref(getRandomMusic());
// 创建音频对象并随机选择音频文件
const audio = new Audio(currentMusic.value.path);

// 控制播放状态和旋转状态
const isPlaying = ref(false);
const warnFlag = ref(true);

// 是否已获得自动播放权限
const hasAutoplayPermission = ref(false);

// 请求自动播放权限
const requestAutoplayPermission = async () => {
  try {
    // 检查是否已有权限
    if (!hasAutoplayPermission.value) {
      // 尝试播放音频以请求权限
      await audio.play();
      hasAutoplayPermission.value = true; // 标记为已获得权限
    }
    // 如果已经有权限，切换播放状态
    togglePlayback();
  } catch (error) {
    if (warnFlag.value) {
      ElMessage.warning('🎶请允许本站自动播放音乐或手动播放🎶');
    }
    warnFlag.value = false;
  }
};

// 切换播放/暂停
const togglePlayback = () => {
  if (isPlaying.value) {
    // 如果正在播放，则暂停
    audio.pause();
  } else {
    // 如果未播放，则开始播放
    audio.loop = true; // 单曲循环
    audio.play().catch((error) => {
      ElMessage.error('播放音乐失败');
    });
  }
  // 切换播放状态
  isPlaying.value = !isPlaying.value;
};

// 添加键盘事件处理函数
const handleKeyPress = (event: KeyboardEvent) => {
  if (event.code === 'Space' && !event.repeat) {
    event.preventDefault(); // 防止页面滚动
    requestAutoplayPermission();
  }
};

// 修改 onMounted
onMounted(() => {
  // 检查浏览器是否支持自动播放
  if (document.visibilityState === 'visible') {
    requestAutoplayPermission();
  }
  
  // 添加键盘事件监听
  window.addEventListener('keydown', handleKeyPress);
});

// 修改 onUnmounted
onUnmounted(() => {
  audio.pause();
  audio.currentTime = 0;
  
  // 移除键盘事件监听
  window.removeEventListener('keydown', handleKeyPress);
});
</script>

<style scoped>
.music-player {
  display: flex;
  /* flex-direction: column; */
  justify-content: center;
  align-items: center;
}

.album-cover {
  max-width: 50px;
  border-radius: 50%;
  transition: transform 0.5s linear;
  cursor: pointer;
}

.rotating {
  animation: rotate 5s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.music-player-tooltip {
  font-size: 16px;
  color: #fff;
}
</style>